package cn.afactory.tygz.ui.fragments;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import cn.afactory.tygz.R;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.activities.TopicAddActivity;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.utils.LocalUtils;

/**
 * Created by Kenneth on 15/9/17.
 */
public class TopicAddFragment extends BaseFragment {

    private String topicName;

    private EditText topicNameEdt;
    private EditText topicDesEdt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle data = getArguments();
        if (null != data && data.containsKey(TopicAddActivity.EXT_DATA_TAG)) {
            topicName = data.getString(TopicAddActivity.EXT_DATA_TAG);
        }
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_channel_add, null);
        initView(view);
        return view;
    }

    private void initView(View view){
        initTitleBar();
        topicNameEdt = (EditText)view.findViewById(R.id.channel_name);
        topicDesEdt = (EditText)view.findViewById(R.id.channel_des);
        if (!TextUtils.isEmpty(topicName)) {
            topicNameEdt.setText(topicName);
        }
    }

    private void initTitleBar() {
        setTitleText("创建话题");

        setRightButton("创建", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCreateTopic();
            }
        });
    }

    private void doCreateTopic(){
        String title = topicNameEdt.getText().toString();
        String desc = topicDesEdt.getText().toString();
        if(title == null){
            return ;
        }
        if(desc == null){
            return ;
        }
        showLoadingView("");
        NetManager.getInstance(getActivity()).doCreateTopic(title, desc, new OnResponseListener<Boolean>() {
            @Override
            public void onComplete(boolean isOK, Boolean result, int errorCode, String errorMsg) {
                hideLoadingView();
                if(isOK && result){
                    LocalUtils.showToast(getActivity(),"成功创建话题");
                    getActivity().finish();
                }else{
                    LocalUtils.showToast(getActivity(),errorMsg);
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingView();
                LocalUtils.showToast(getActivity(),errorMessage);
            }
        });
    }
}
